// packageD/mycomponent/yz_wap/yz_wapmap.js
var QQMapWX = require("../../../mymap/qqmap-wx-jssdk.min.js");
var location = require("../../../mybehaviors/location/location");

var qqmapsdk;
// var map;
var app = getApp();
Component({
  behaviors: [location],
  addGlobalClass: true,
  /**
   * 组件的属性列表
   */
  properties: {
    local_city:{
      value:'',
      type:String
    },
    polygons: {
      value: [],
      type: Array
    }
  },
  lifetimes: {
    attached: function () {
      let that = this;
      wx.getSystemInfo({
        success: (result) => {
          console.log(result);
          if(result.platform == 'android'){
            that.setData({
              android:true
            });
          }
        },
      });
      if (!app.globalData.qqmapkey) {
        app._getTemplate().then((res) => {
          qqmapsdk = new QQMapWX({
            key: app.globalData.qqmapkey,
          });
          this.poscurrent();
        });
      } else {
        qqmapsdk = new QQMapWX({
          key: app.globalData.qqmapkey,
        });
        this.poscurrent();
      }
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    android:false,
    suggestion: [],
    address_latitude: "",
    address_longitude: "",
    markers: [],
    address_detail: "",
    suggestionshow: false,
    mksData: [],
    mapmessageData: {
      title: "",
      message: "",
      latitude: "",
      longitude: "",
      city: "",
    },
    updatePoint: {},
    scaleData: 16,
    tag: "",
    imgPath: app.globalData.imgPath,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    searchconfirmbtn(e) {
      var val = e.detail.value;
      this.addressinp(val);
    },
    addressinpbtn(e) {
      var val = e.detail.value;
      this.addressinp(val);
    },
    addressinp(val) {
      var _this = this;
      if (!val) {
        this.setData({
          suggestionshow: false,
        });
        return;
      }
      //调用关键词提示接口
      qqmapsdk.getSuggestion({
        //获取输入框值并设置keyword参数
        keyword: val, //用户输入的关键词，可设置固定值,如keyword:'KFC'
        region: this.data.local_city, //设置城市名，限制关键词所示的地域范围，非必填参数
        region_fix: 1,
        sig: app.globalData.qqmapsig,
        success: function (res) {
          //搜索成功后的回调
          var sug = [];
          for (var i = 0; i < res.data.length; i++) {
            sug.push({
              // 获取返回结果，放到sug数组中
              title: res.data[i].title,
              id: res.data[i].id,
              addr: res.data[i].address,
              city: res.data[i].city,
              district: res.data[i].district,
              latitude: res.data[i].location.lat,
              longitude: res.data[i].location.lng,
            });
          }
          _this.setData({
            //设置suggestion属性，将关键词搜索结果以列表形式展示
            suggestion: sug,
            suggestionshow: true,
          });
        },
        fail: function (error) {
          console.error(error);
        },
        complete: function (res) {},
      });
    },
    //数据回填方法
    backfill: function (e) {
      var id = e.currentTarget.id;
      for (var i = 0; i < this.data.suggestion.length; i++) {
        if (i == id) {
          this.setData({
            address_detail: this.data.suggestion[i].title,
            address_latitude: this.data.suggestion[i].latitude,
            address_longitude: this.data.suggestion[i].longitude,
            "mapmessageData.title": this.data.suggestion[i].title,
            "mapmessageData.message": this.data.suggestion[i].addr,
            "mapmessageData.latitude": this.data.suggestion[i].latitude,
            "mapmessageData.longitude": this.data.suggestion[i].longitude,
            "mapmessageData.city": this.data.suggestion[i].city,
            suggestionshow: false,
          });
          this.nearby_search();
        }
      }
    },
    // 事件触发，调用接口
    nearby_search: function () {
      var _this = this;
      // 调用接口
      qqmapsdk.search({
        keyword: this.data.address_detail, //搜索关键词
        region: this.data.local_city,
        location: {
          latitude: this.data.address_latitude,
          longitude: this.data.address_longitude,
        }, //设置周边搜索中心点
        sig: app.globalData.qqmapsig,
        success: function (res) {
          //搜索成功后的回调
          console.log("ccccc", res);
          var mks = [];
          var mksData = [];
          for (var i = 0; i < res.data.length; i++) {
            mks.push({
              // 获取返回结果，放到mks数组中
              title: res.data[i].title,
              id: res.data[i].id,
              latitude: res.data[i].location.lat,
              longitude: res.data[i].location.lng,
              zIndex: 10,
              iconPath: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png", //图标路径
              width: 20,
              height: 25,
              callout: {
                padding: "10rpx",
                borderRadius: "5rpx",
                content: res.data[i].title,
              },
            });
            mksData.push({
              address: res.data[i].address,
              title: res.data[i].title,
              latitude: res.data[i].location.lat,
              longitude: res.data[i].location.lng,
              id: res.data[i].id,
              city: res.data[i].ad_info.city ?
                res.data[i].ad_info.city :
                res.res.data[i].ad_info.province,
            });
          }
          _this.setData({
            //设置markers属性，将搜索结果显示在地图中
            markers: mks,
            mksData: mksData,
          });
        },
        fail: function (res) {
          console.log(res);
        },
        complete: function (res) {
          // console.log(res);
        },
      });
    },
    getmarkertap(e) {
      let markerId = e.markerId;
      if(markerId == '-1') {
        this.setData({
          "mapmessageData.title": "",
          "mapmessageData.message": "自选位置",
          "mapmessageData.latitude": this.data.updatePoint.latitude,
          "mapmessageData.longitude": this.data.updatePoint.longitude,
          address_latitude: this.data.updatePoint.latitude,
          address_longitude: this.data.updatePoint.longitude,
        });
      }
      for (var i = 0; i < this.data.mksData.length; i++) {
        let id = this.data.mksData[i].id;
        if (markerId == id) {
          // markerId == id 要真机预览调试才可以
          this.setData({
            address_latitude: this.data.mksData[i].latitude,
            address_longitude: this.data.mksData[i].longitude,
            "mapmessageData.title": this.data.mksData[i].title,
            "mapmessageData.message": this.data.mksData[i].address,
            "mapmessageData.latitude": this.data.mksData[i].latitude,
            "mapmessageData.longitude": this.data.mksData[i].longitude,
            "mapmessageData.city": this.data.mksData[i].city,
          });
        }
      }
    },
    maptap(e) {
      // 真机触发了getmarkertap就不会触发maptap
      if(!this.data.polygons || this.data.polygons.length <= 0) {
        return;
      }
      console.log(e,"maptap");
      let updatePoint = {
        // 获取返回结果，放到mks数组中
        title: '自选位置',
        id: '-1',
        latitude: e.detail.latitude,
        longitude: e.detail.longitude,
        zIndex: 2,
        iconPath: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png", //图标路径
        width: 20,
        height: 25,
        callout: {
          padding: "10rpx",
          borderRadius: "5rpx",
          content: '自选位置',
        },
      };
      if(this.data.markers && this.data.markers.length > 0 && this.data.markers[this.data.markers.length -1].id != '-1') {
        this.data.markers.push(updatePoint);
      }else {
        this.data.markers[this.data.markers.length -1] = updatePoint;
      }
     
      this.setData({
        updatePoint: updatePoint,
        //设置markers属性，将搜索结果显示在地图中
        markers: this.data.markers,
        "mapmessageData.title": "",
        "mapmessageData.message": "自选位置",
        "mapmessageData.latitude": e.detail.latitude,
        "mapmessageData.longitude": e.detail.longitude,
        address_latitude: e.detail.latitude,
        address_longitude: e.detail.longitude,
      });
    },
    addbtn() {
      let mapCtx = wx.createMapContext("myMap",this);
      // console.log(mapCtx);
      let that = this;
      mapCtx.getScale({
        success: function (e) {
          let scale = e.scale;
          that.setData({
            scaleData: scale + 1,
          });
        },
      });
    },
    minusbtn() {
      let mapCtx = wx.createMapContext("myMap",this);
      let that = this;
      mapCtx.getScale({
        success: function (e) {
          let scale = e.scale;
          that.setData({
            scaleData: scale - 1,
          });
        },
      });
    },
    addressplay() {
      this.poscurrent();
    },
    poscurrent: function () {
      let that = this;
      wx.getSetting({
        success(resData) {
          if (!resData.authSetting["scope.userLocation"]) {
            wx.authorize({
              scope: "scope.userLocation",
              success() {},
              fail() {},
              complete() {
                that.getlocaldata();
              },
            });
          } else {
            that.getlocaldata();
          }
        },
      });

    },
    getlocaldata() {
      this._getLocation((mapdata, e) => {
        this.setData({
          address_detail: "",
          address_latitude: mapdata.location.lat,
          address_longitude: mapdata.location.lng,
          "mapmessageData.title": mapdata.formatted_addresses.recommend,
          "mapmessageData.address_component": mapdata.formatted_addresses,
          "mapmessageData.message": mapdata.address,
          "mapmessageData.latitude": mapdata.location.lat,
          "mapmessageData.longitude": mapdata.location.lng,
          "mapmessageData.city": mapdata.address_component.city
            ? mapdata.address_component.city
            : mapdata.address_component.province,
        });
      });
      
    },
    onClickLeft(){
      this.triggerEvent('confirm', 'noshow');
    },
    buttonbtn() {
      let point = {
        lat: Number(Number(this.data.address_latitude).toFixed(6)),
        lng: Number(Number(this.data.address_longitude).toFixed(6)),
        address:this.data.mapmessageData.title
      };
      if(!this.data.polygons || this.data.polygons.length <= 0) {
        wx.setStorage({
          key: "address-point",
          data: {
            point: point,
            city: this.data.mapmessageData.city,
          },
        });
      }
      this.triggerEvent('confirm', point);
    },
  }
});